#include<iostream>
using namespace std;
#include<vector>
#include<queue>
int arr[26] = { 0 };
class Solution {
public:
    class cmp {
    public:
        bool operator()(char a1, char a2) {
            return arr[a1 - 'A'] < arr[a2 - 'A'];
        }
    };
    int leastInterval(vector<char>& tasks, int n) {
        int ans = 0;
        for (auto& e : tasks)
            ++arr[e - 'A'];
        priority_queue<char, vector<char>, cmp> que;
        for (int i = 0; i < 26; ++i)
            if (arr[i])
                que.push('A' + i);
        while (que.size())
        {
            int now = n + 1, count = 0;
            vector<char> help;
            while (now--)
            {
                if (que.size())
                {
                    ++ans;
                    --arr[que.top() - 'A'];
                    if (arr[que.top() - 'A'])
                        ++count;
                    help.emplace_back(que.top());
                    que.pop();
                }
                else {
                    if (count == 0)
                        return ans;
                    ans += now + 1;
                    now = 0;
                }
            }
            for (auto& e : help)
                if (arr[e - 'A'])
                    que.push(e);
        }
        return ans;
    }
};
int main() {
    vector<char> tesks{ 'A','A','A','B','B','B' };
    Solution().leastInterval(tesks, 2);
}